package com.caigou.modules.info.viewmodel

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.utils.Logger
import com.caigou.modules.info.bean.InfoBean
import com.caigou.modules.info.respository.InfoRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author #Suyghur.
 * Created on 2021/11/20
 */
@HiltViewModel
class MyInfoViewModel @Inject constructor(private val repository: InfoRepository) : ViewModel() {

    val myInfoListLiveData = MutableLiveData<Resource<InfoBean>>()
    val myCollectedListLiveData = MutableLiveData<Resource<InfoBean>>()

    fun getMyInfoList(page: Int, limit: Int, userId: String, checkStatus: Int) {
        myInfoListLiveData.value = Resource.Loading()
        viewModelScope.launch {
            repository.getMyInfoList(page, limit, userId, checkStatus)
                .map {
                    if (it.code == 0) {
                        Resource.Success(it.data)
                    } else {
                        Resource.DataError(it.code, it.msg)
                    }
                }
                .catch {
                    val message = if (TextUtils.isEmpty(it.message)) {
                        ""
                    } else {
                        it.message!!
                    }
                    Resource.DataError<InfoBean>(-1, message)
                    Logger.e("catch: ${it.message}")
                }
                .collectLatest {
                    myInfoListLiveData.value = it
                }
        }

    }

    fun getMyCollectedList(page: Int, limit: Int, userId: String) {
        myCollectedListLiveData.value = Resource.Loading()
        viewModelScope.launch {
            repository.getMyCollectedList(page, limit, userId)
                .map {
                    if (it.code == 0) {
                        Resource.Success(it.data)
                    } else {
                        Resource.DataError(it.code, it.msg)
                    }
                }
                .catch {
                    val message = if (TextUtils.isEmpty(it.message)) {
                        ""
                    } else {
                        it.message!!
                    }
                    Resource.DataError<InfoBean>(-1, message)
                    Logger.e("catch: ${it.message}")
                }
                .collectLatest {
                    myCollectedListLiveData.value = it
                }
        }
    }
}